from decimal import Decimal
from apps.system.user.dao import UserDao
from apps.pay.recordIncomes.dao import RecordIncomesDao
from apps.chat.message.functions import MessageFun
from apps.system.lessee.dao import LesseeDao
from django.db.models import Sum
from datetime import datetime
from django.db.models import F
import json

# 自动释放
def autoFreeBalanceLockedRecord(date):
    lessee = LesseeDao().getLessee()
    if lessee.openFree is False:
        return
    
    # 周六周日不释放
    if lessee.openFreeForWeekend is False:
        today = datetime.today()
        week_day = today.weekday()
        if week_day == 6 or week_day == 7:
            return
    # 自动释放金额为日释放池的50%
    freeMoneyDay = lessee.freePoolDay * Decimal(0.5)
    freeBalanceLockedRecord(date, freeMoneyDay)
        
# 每个锁仓单子按照顺序排队释放
def freeBalanceLockedRecord(date, freeMoneyDay):
    lessee = LesseeDao().getLessee()

    freeMoneyDay = Decimal(freeMoneyDay)

    # 平台当日发放释放额度,VIP会员才开始释放,且是释放日期当天及之前升级的VIP
    print('date', date)
    users = UserDao().findAll().filter(role='custom', rank__grade__gt=1)
    print('平台当日发放释放额度', freeMoneyDay, '用户数', users.count(), UserDao().findAll().filter(role='custom', rank__grade__gt=1).count())
    freeMoneysTotal = 0
    for user in users:
        # 查找锁仓记录
        recordIncomes = RecordIncomesDao().findAll().filter(createTime__lt=date, payway='incomesLocked', changeWay='add', moneyLocked__gt=0, user=user).order_by('createTime')
        print('锁仓记录', recordIncomes.count(), RecordIncomesDao().findAll().filter(payway='incomesLocked', changeWay='add', moneyLocked__gt=0, user=user).order_by('createTime').count())
        if recordIncomes.count() == 0:
            continue
        # 计算释放系数
        contributionValueForTotal = RecordIncomesDao().findAll().filter(createTime__lt=date, payway='contributionValue', changeWay='add', money__gt=0).aggregate(sums=Sum('money'))['sums'] or 0
        contributionValueForUser = RecordIncomesDao().findAll().filter(createTime__lt=date, payway='contributionValue', changeWay='add', money__gt=0, user=user).aggregate(sums=Sum('money'))['sums'] or 0
        rate = Decimal(contributionValueForUser) / Decimal(contributionValueForTotal)
        if contributionValueForUser == 0:
            continue
        freeMoneyForUser = (freeMoneyDay * rate).quantize(Decimal('0.00'))
        print('释放用户', user.id, '贡献值', contributionValueForTotal, contributionValueForUser, '释放系数', rate, '释放数量', freeMoneyForUser)
        
        freeMoneys = 0
        for recordIncome in recordIncomes:
            if recordIncome.moneyLocked > freeMoneyForUser:  # 如果锁仓金额足够释放，正常释放，否则先把这条单子释放，再找下一条释放
                print('足够释放', recordIncome.moneyLocked, freeMoneyForUser)
                recordIncome.moneyLocked = F('moneyLocked') - freeMoneyForUser
                # 添加释放时间和金额
                freeRecord = addFreeRecord(recordIncome.freeRecord, {'createTime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'money': str(freeMoneyForUser)})
                recordIncome.freeRecord = freeRecord
                recordIncome.save()
                # 汇总释放金额
                freeMoneys = Decimal(freeMoneys) + freeMoneyForUser
                break
            else:
                print('释放完', recordIncome.moneyLocked)
                realFree = recordIncome.moneyLocked
                recordIncome.moneyLocked = 0
                # 添加释放时间和金额
                freeRecord = addFreeRecord(recordIncome.freeRecord, {'createTime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'money': str(realFree)})
                recordIncome.freeRecord = freeRecord
                recordIncome.save()
                # 汇总释放金额
                freeMoneys = Decimal(freeMoneys) + realFree
                freeMoneyForUser = freeMoneyForUser - realFree
                # 锁仓释放完成之后，收回订单号相同的贡献值
                recordIncomesForContributionValue = RecordIncomesDao().findAll().filter(shop__isnull=True, orderId = recordIncome.orderId, payway='contributionValue', changeWay='add', money__gt=0)
                print('锁仓释放完的订单', recordIncome.orderId, '订单号相同的贡献值奖励订单', recordIncomesForContributionValue )
                for recordIncomeForContributionValue in recordIncomesForContributionValue:
                    contributionValue = Decimal(recordIncomeForContributionValue.money)
                    recordIncomeForContributionValue.money = 0
                    recordIncomeForContributionValue.remark = '同源锁仓补贴释放完成贡献值' + str(contributionValue) + '清零'
                    recordIncomeForContributionValue.save()
                    # 减少用户贡献值
                    payway = 'contributionValue'
                    UserDao().subWallet(payway, recordIncomeForContributionValue.user, contributionValue)
                    data = {}
                    data['scene'] = 'lockedFree'
                    data['user'] = recordIncomeForContributionValue.user.id
                    data['fromUser'] = user.id
                    data['orderId'] = recordIncomeForContributionValue.orderId
                    data['money'] = contributionValue
                    data['payway'] = payway
                    data['changeWay'] = 'sub'
                    data['remark'] = '同源锁仓补贴释放完成扣除贡献值'
                    data['orderStatus'] = 'FINISH'
                    RecordIncomesDao().create(data)
                # 继续找下一单释放
                continue
            
            
        if freeMoneys == 0:
            continue
        else:
            freeMoneysTotal = freeMoneysTotal + freeMoneys
        # 锁仓资产释放记录
        _payway = 'incomesLocked'
        UserDao().subWallet(_payway, user, freeMoneys)
        data = {}
        data['lessee'] = lessee.id
        data['scene'] = 'lockedFree'
        data['user'] = user.id
        data['fromUser'] = user.id
        data['orderId'] = ''
        data['money'] = freeMoneys
        data['payway'] = _payway
        data['changeWay'] = 'sub'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)
        # 增加可用积分
        _payway = 'incomes'
        UserDao().addWallet(_payway, user, freeMoneys)
        data = {}
        data['lessee'] = lessee.id
        data['scene'] = 'lockedFree'
        data['user'] = user.id
        data['fromUser'] = user.id
        data['orderId'] = ''
        data['money'] = freeMoneys
        data['payway'] = _payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)
    
    print('实际释放金额', freeMoneysTotal)
    
    # 日释放资金池
    if freeMoneysTotal > 0:
        # 日释放池
        freePoolDays = freeMoneysTotal
        payway = 'freePoolDay'
        LesseeDao().subWallet(payway, freePoolDays)
        data = {}
        data['scene'] = 'lockedFree'
        data['user'] = ''
        data['fromUser'] = ''
        data['orderId'] = ''
        data['money'] = freePoolDays
        data['payway'] = payway
        data['changeWay'] = 'sub'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)
    return freeMoneysTotal

def freePoolMonth(cycle, freeMoney):
    if cycle == 'month':
        freeMoney = Decimal(freeMoney).quantize(Decimal('0.00'))
        payway = 'freePoolMonth'
        LesseeDao().subWallet(payway, freeMoney)
        data = {}
        data['scene'] = 'freeForMonth'
        data['user'] = ''
        data['fromUser'] = ''
        data['orderId'] = ''
        data['money'] = freeMoney
        data['payway'] = payway
        data['changeWay'] = 'sub'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)
        # 增加日释放池
        payway = 'freePoolDay'
        LesseeDao().addWallet(payway, freeMoney)
        data = {}
        data['scene'] = 'freeForMonth'
        data['user'] = ''
        data['fromUser'] = ''
        data['orderId'] = ''
        data['money'] = freeMoney
        data['payway'] = payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)

def addFreeRecord(freeRecord, data):
    freeRecordList = []
    if freeRecord:
        freeRecordList = json.loads(freeRecord)
    freeRecordList.insert(0, data)
    freeRecord = json.dumps(freeRecordList)
    return freeRecord


# 这种释放方式是每个单子每天都按照设置的释放比例释放
def freeBalanceLockedRecord1():
    lessee = LesseeDao().getLessee()

    if lessee.openFree is False:
        return
    
    # 周六周日不释放
    if lessee.openFreeForWeekend is False:
        today = datetime.today()
        week_day = today.weekday()
        if week_day == 6 or week_day == 7:
            return

    users = UserDao().findAll().filter(role='custom')
    for user in users:
        # 查找锁仓记录
        recordIncomes = RecordIncomesDao().findAll().filter(user=user, payway='incomesLocked', moneyLocked__gt=0).order_by('-createTime')
        freeMoneys = 0
        for recordIncome in recordIncomes:
            freeMoney = Decimal(recordIncome.money * lessee.freeRate).quantize(Decimal('0.00'))
            if recordIncome.moneyLocked < freeMoney:  # 如果锁仓金额不足，全部释放
                freeMoney = recordIncome.moneyLocked
                recordIncome.moneyLocked = 0
                recordIncome.save()
            else:
                freeMoney = freeMoney
                recordIncome.moneyLocked = F('moneyLocked') - freeMoney
                recordIncome.save()
            # 汇总释放金额
            freeMoneys = Decimal(freeMoneys) + freeMoney
        if freeMoneys == 0:
            continue
        # 锁仓资产释放记录
        _payway = 'balanceLocked'
        UserDao().subWallet(_payway, user, freeMoneys)
        data = {}
        data['lessee'] = lessee.id
        data['scene'] = 'lockedFree'
        data['user'] = user.id
        data['fromUser'] = user.id
        data['orderId'] = ''
        data['money'] = freeMoneys
        data['payway'] = _payway
        data['changeWay'] = 'sub'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)
        # 增加流动资产
        _payway = 'balance'
        UserDao().addWallet(_payway, user, freeMoneys)
        data = {}
        data['lessee'] = lessee.id
        data['scene'] = 'lockedFree'
        data['user'] = user.id
        data['fromUser'] = user.id
        data['orderId'] = ''
        data['money'] = freeMoneys
        data['payway'] = _payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)

def countAwardForRider(self, params):
    _user = params.get('user')
    _payway = params.get('payway')
    money = (Decimal(params.get('realPay')) * Decimal(params.get('awardForRider'))).quantize(Decimal('0.00'))
    UserDao().addWallet(_payway, _user, money)
    data = {}
    data['scene'] = params.get('scene')
    data['user'] = _user.id
    data['fromUser'] = _user.id
    data['orderId'] = params.get('orderId')
    data['money'] = money
    data['payway'] = _payway
    data['changeWay'] = 'add'
    data['orderStatus'] = 'FINISH'
    RecordIncomesDao().create(data)
    MessageFun().sendMessage(None, _user, 'system', {'title': '奖励通知', 'content': '您有一笔任务奖励已发放，请前往钱包查看。'})